//
//  SCRefresh.swift
//  weibo
//
//  Created by 阿城 on 15/12/11.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

private let refreshViewH: CGFloat = 40
enum RefreshState : Int{
    case Nomal
    case Refreshing
    case PrepareRefresh
}

class SCRefresh: UIControl {

    private var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func willMoveToSuperview(newSuperview: UIView?) {
        if let view = newSuperview as? UIScrollView{
            scrollView = view

            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            //设置frame
            frame = CGRect(x: 0, y: -refreshViewH, width: scrollView!.bounds.width, height: refreshViewH)
            
            initailInset = scrollView?.contentInset.top ?? 0
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if keyPath == "contentOffset"{
//            printLog(change)
            let contentOffsetY = scrollView?.contentOffset.y
            let contentInset = scrollView?.contentInset.top ?? 0
            
//            printLog(contentOffsetY)
            //不在刷新时
            if controlState != .Refreshing{
                if isDrag{
                    if contentOffsetY > -(refreshViewH + contentInset){
                        controlState = .Nomal
                    }else{
                        controlState = .PrepareRefresh
                    }
                }else{
                    if controlState == .PrepareRefresh{
                        controlState = .Refreshing
                    }
                }
            }
        }
    }
    
    private var isDrag: Bool {
        if let scroll = scrollView{
            return scroll.dragging
        }
        return false
    }
    
    private var initailInset: CGFloat = 0
    
    private var controlState: RefreshState = .Nomal{
        didSet{
            switch controlState{
            //正常
            case .Nomal:
//                printLog("Nomal")
                messageLabel.text = "下拉刷新"
                indicator.stopAnimating()
                arrowIcon.hidden = false
//                self.scrollView?.contentInset.top = initailInset
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
            case .Refreshing:
//                printLog("Refreshing")
                messageLabel.text = "正在刷新"
                arrowIcon.hidden = true
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.indicator.startAnimating()
                    self.scrollView?.contentInset.top += refreshViewH
                })
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
        
                
            case .PrepareRefresh:
//                printLog("PrepareRefresh")
                messageLabel.text = "放松起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            }
        }
    }
    
    func endLoading(){
        controlState = .Nomal
        UIView.animateWithDuration(0.25) { () -> Void in
            self.scrollView?.contentInset.top -= refreshViewH
        }
    }
    
    
    private func setupUI(){
        
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicator)
        
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(10)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    
    // MARK: - 懒加载控件
    // 箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 显示文字的label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(titleText: "下拉刷新", color: UIColor.grayColor(), fontSize: 12)
        return label
    }()
    // 菊花转
    private lazy var indicator: UIActivityIndicatorView = {
        let indic = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        return indic
    }()
    
    deinit{
        if let scroll = scrollView {
            self.removeObserver(scroll, forKeyPath: "contentOffset")
        }
    }
}
